﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Fetion.Core
{

    class DataBuffer 
    {

        public byte[] Data;
        private int mLength;
        private int mPostion = 0;
        internal int mCount = 0;
        public DataBuffer(byte[] data)
        {
            Data = data;
            mLength = data.Length;
            mPostion = 0;
            mCount = data.Length;
        }
        public DataBuffer(int length)
        {
            mLength = length;
            Data = new byte[length];
        }
        public void From(Array source, int index, int count)
        {
            Buffer.BlockCopy(source, index, Data, 0, count);
            mPostion = 0;
            mCount = count;
        }
        private int _count;
        public int Write(byte[] data, int _index, int _length)

        {
           
         
            _count = 0;
        
                if (mPostion + _length > mLength)
                {
                    _count = mLength - mPostion;
                }
                else
                {
                    _count = _length;
                }
                if (_count > 0)
                {

                    Buffer.BlockCopy(data, _index, Data, mPostion, _count);
                    mPostion += _count;
                    mCount += _count;
                }
            
          
            return _count;
        }
        private int _end;
        private ByteArraySegment mByteSegment = new ByteArraySegment();
        public ByteArraySegment Read(int count)
        {
            _end = count;
            if (mPostion + count > mCount)
                _end = mCount - mPostion;
            mByteSegment.SetInfo(Data, mPostion, _end);
            
            mPostion += _end;
            return mByteSegment;
        }
        public void Seek()
        {
            Seek(0);
        }
        public void Seek(int postion)
        {
            mPostion = 0;
        }
        public ByteArraySegment GetSegment()
        {
            mByteSegment.SetInfo(Data, 0, mCount);
            return mByteSegment;
            
        }
        
        
       
    }
   
  
   
}
